<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 130px">
            <el-option label="付款单号" value="payment_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="采购单号/SKU" value="purchase_no_sku"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" @search="query" class="w-60" />
        </VGroup>
        <VSelect v-model="form.payment_status" placeholder="财务状态" :options="options.payment_status || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.payment_item" placeholder="付款项目" :options="options.payment_item" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.feishu_audit_status" placeholder="飞书审批状态" :options="options.feishu_audit_status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple collapse-tags />
        <VSelect v-model="form.purchase_type" placeholder="供应商类型" :options="options.purchase_type || []" style="min-width: 160px" multiple collapse-tags />
        <VSelect v-model="form.company_id" placeholder="公司主体" :options="options.company_id || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.payment_type" placeholder="付款方式" :options="options.payment_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags style="min-width: 220px" />
        <VSelect v-model="form.next_audit_role_id" placeholder="审批节点" :options="options.opt_role" multiple collapse-tags style="min-width: 220px" />
        <VCascader v-model="form.create_user_id" placeholder="请款人" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.payment_user_id" placeholder="付款人" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.apply_payment_type" placeholder="申请付款类型" :options="options.apply_payment_type || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_equal_inbound" placeholder="入库金额与实际申请付款金额是否相等" :options="options.is_equal_inbound || []" multiple collapse-tags style="min-width: 292px" />
        <VSelect v-model="form.purchase_status" placeholder="采购状态" :options="options.purchase_status || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.trade_type" placeholder="线上交易方式" :options="options.trade_type || []" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.pay_type" placeholder="1688支付方式" :options="options.pay_type" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <el-input v-model="form.audit_remark" placeholder="审核驳回原因" class="w-60" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="请款时间" value="create_time"></el-option>
            <el-option label="付款时间" value="payment_time"></el-option>
            <el-option label="当天还款日" value="period_date"></el-option>
            <el-option label="期望付款时间" value="except_payment_time"></el-option>
            <el-option label="最后结算时间" value="last_settlement_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/finance/payment/alipay" type="primary" :loading="loadings.pay1" @click="handlePay(1)">
          支付宝付款</VButton>
        <VButton auth="/purchase/finance/payment/creditpay" type="primary" :loading="loadings.pay2" @click="handlePay(2)">
          诚E赊付款</VButton>
        <VButton auth="/purchase/finance/payment/borderpay" type="primary" :loading="loadings.pay3" @click="handlePay(3)">
          跨境宝付款</VButton>
        <VButton auth="/purchase/finance/payment/fast" type="primary" @click="payRef.open()">1688快速支付</VButton>
        <VAudit auth="/purchase/finance/payment/audit" field="p_id" url="/v1/finance/payment/batch-audit" :tableRef="tableRef" @success="query" />
        <VButton auth="/purchase/finance/payment/void" @click="handleBatch('cancel')">批量作废</VButton>
        <VButton auth="/purchase/finance/payment/void" :loading="loadings.print" @click="handleBatch('print')">批量打印
        </VButton>
        <VButton auth="/purchase/finance/payment/submit" :loading="loadings.print" @click="handleBatch('submit')">批量提交
        </VButton>
        <VButton auth="/purchase/finance/payment/back" :loading="loadings.print" @click="handleBatch('back')">批量撤回
        </VButton>
        <VButton auth="/purchase/finance/payment/cashierReject" :loading="loadings.cashierReject" @click="handleBatch('cashierReject')">出纳驳回</VButton>
        <VButton auth="/purchase/finance/payment/editPayment" :loading="loadings.editPayment" @click="handleBatch('editPayment')">修改付款凭证</VButton>
        <VExport auth="/purchase/finance/payment/export" mainKey="p_id" :name="baseName" :tableRef="tableRef" task class="ml-auto" />
        <VTotal ref="totalRef" auth="/purchase/finance/payment/total" url="/v1/finance/payment/total"
          :options="[{ title: '待付款', key: 'wait_payment' }, { title: '即将逾期', key: 'overdue_soon' }, { title: '已逾期', key: 'overdue' }, { title: '线上待付款', key: 'online' }, { title: '阿里账期待还款', key: 'period' }, { title: '已付款', key: 'pay' }]"
          :child="[{ title: '单量', key: 'num' }, { title: '金额', key: 'price' }]" class="w-full" />
      </template>
    </VTable>
    <VLog ref="logRef" />
    <PrintPay ref="printPayRef" />
    <PrintDetail ref="printDetailRef" />
    <BatchPrint ref="batchPrintRef" />
    <EditPayment ref="editPaymentRef" @success="query" />
    <CashierReject ref="cashierRejectRef" :options="options" @success="query" />
    <ApplyPayment ref="applyPaymentRef" :options="options" @success="query" />
    <Pay ref="payRef" :options="options" @success="query" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import VTotal from '@/components/VTotal'
import ApplyPayment from './components/ApplyPayment'
import Pay from './components/Pay'
import BatchPrint from './components/BatchPrint'
import PrintPay from './components/PrintPay'
import CashierReject from './components/CashierReject'
import PrintDetail from './components/PrintDetail'
import EditPayment from './components/EditPayment'
import { getOption } from '@/api/public'
import { resMessage } from '@/utils/res'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

const baseName = 'payment'
const tableRef = ref()
const logRef = ref()
const payRef = ref()
const totalRef = ref()
const applyPaymentRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: 'purchase' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
  api.getTradeType().then(res => {
    options.value.trade_type = res.data
  })
  api.getPayType().then(res => {
    options.value.pay_type = res.data
  })
})

// 支付
const handlePay = (payment_type) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const p_ids = selection.map(d => d.p_id)
  loadings['pay' + payment_type] = true
  api.onlinePay({ payment_type, p_ids }).then(res => {
    const { payment_message, url } = res.data
    if(payment_message) {
      ElMessageBox.alert(payment_message || '找冬雪', '提示', {
        showConfirmButton: false,
        showCancelButton: true,
        cancelButtonText: '关闭'
      })
    }
    url.forEach(d => {
      window.open(d, '_blank', 'height=700, width=1200, top=200, left=300,toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')
    })
  }).finally(() => {
    loadings['pay' + payment_type] = false
  })
}

// 批量操作
const auditRef = ref()
const batchPrintRef = ref()
const editPaymentRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const p_ids = selection.map(d => d.p_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    editPayment: () => {
      editPaymentRef?.value.open(p_ids)
    },
    submit: () => {
      showLoading()
      api.submit({ p_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    back: () => {
      showLoading()
      api.back({ p_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    print: async () => {
      batchPrintRef?.value.open(p_ids)
    },
    cashierReject: () => {
      cashierRejectRef?.value.open(p_ids)
    },
    audit: () => {
      const firstItem = selection[0]
      if (selection.some(d => d.payment_status !== firstItem.payment_status)) {
        ElMessage.warning('请选择同一付款状态的付款单')
        return
      }
      auditRef?.value.open(selection, { label: '批量审核', value: 1 })
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.batchCancel({ p_ids }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}

// 单行操作
const printPayRef = ref()
const printDetailRef = ref()
const cashierRejectRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { p_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    printPay: () => {
      printPayRef?.value.view(p_id)
    },
    printDetail: () => {
      printDetailRef?.value.print(p_id)
    },
    look: () => {
      applyPaymentRef?.value.open([p_id], { look: true })
    },
    edit: () => {
      applyPaymentRef?.value.open([p_id], { edit: true })
    },
    cashierReject: () => {
      cashierRejectRef?.value.open([p_id])
    },
    submit: () => {
      showLoading()
      api.submit({ p_ids: [p_id] }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    contract: () => {

    },
    pay: () => {
      applyPaymentRef?.value.open([p_id], { pay: true })
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.batchCancel({ p_ids: [p_id] }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    toAbnormal: () => {
      sessionStorage.setItem('_table_form', JSON.stringify({ tableForm: { purchase_nos: row.purchase_no } }))
      router.push('/manage/abnormal')
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, p_id })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 114 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'payment_no', value: '' },
      dateRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      minWidth: 150, slots: {
        header: () => <div>付款单号</div>,
        default: ({ row }) => <div>
          <VText value={row.payment_no} type='link' onClick={() => handleRow('look', row)} />
          <VText title='线上交易方式' value={row.trade_type_name} title-position='top' />
          <VText title='支付方式' value={row.pay_type_name?.join(',')} />
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>财务状态</div>,
        default: ({ row }) => <div>
          <VText value={row.payment_status_name} />
          <VText title='审批节点' value={row.next_audit_role_name} />
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>飞书审批状态</div>,
        default: ({ row }) => <div>
          <VText title='状态' value={row.feishu_audit_status_name} />
          <VText title='节点' value={row.feishu_next_audit_role_name} />
        </div>
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>当天还款日</div>,
        default: ({ row }) => <VText value={row.period_date} line={2} />
      }
    },
    {
      minWidth: 240, slots: {
        header: () => <div>供应商<br />结算方式/供应商类型/交易方式<br />是否异常未处理</div>,
        default: ({ row }) => <div>
          <VText value={row.supplier_name} line={1} />
          <VText title='结算方式' value={row.period_name} line={1}></VText>
          <VText title='供应商类型' value={row.purchase_type_name}></VText>
          <VText title='交易方式' value={row.payment_type_name}></VText>
          <VText title='是否异常未处理' value={row.abnormal_status} type={row.abnormal_num ? 'link' : undefined} onClick={() => handleRow('toAbnormal', row)}></VText>
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>公司主体<br />付款申请类型</div>,
        default: ({ row }) => <div>
          <VText value={row.company_id_name} line={2} />
          <div>{row.apply_payment_type_name}</div>
        </div>
      }
    },
    {
      minWidth: 150, slots: {
        header: () => <div>采购单号</div>,
        default: ({ row }) => {
          const purchase_no = row.purchase_no || []
          return <div>
            {purchase_no.filter((d, i) => i < 2).map(d => <div>{d}</div>)}
            <VText value='查看详情' type='button' onClick={() => handleRow('look', row)} />
          </div>
        }
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>下单金额</div>,
        default: ({ row }) => <VText value={row.order_price} />
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>应付金额</div>,
        default: ({ row }) => <VText value={row.payable_price} />
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>运费</div>,
        default: ({ row }) => <VText value={row.total_tracking_price} />
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>售后<br/>折扣</div>,
        default: ({ row }) => <div>
        <VText value={row.after_sale_price} />
        <VText value={row.preferential_price} />
        </div>
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>已付金额</div>,
        default: ({ row }) => row.purchase_payment_price
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>申请金额</div>,
        default: ({ row }) => row.apply_price
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>付款金额</div>,
        default: ({ row }) => row.payment_price
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>退款金额</div>,
        default: ({ row }) => row.refund_price
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>未入库金额</div>,
        default: ({ row }) => row.not_inbound_price
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>已入库金额</div>,
        default: ({ row }) => row.inbound_price
      }
    },
    {
      minWidth: 110, slots: {
        header: () => <div>入库金额与实际申请付款金额是否相等</div>,
        default: ({ row }) => row.is_equal_inbound_name
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>期望付款时间<br />最后结算时间</div>,
        default: ({ row }) => <div>
          <div>{row.except_payment_time}</div>
          <div>{row.last_settlement_time}</div>
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>请款人<br />请款时间</div>,
        default: ({ row }) => <div>
          <div>{row.create_user}</div>
          <div>{row.create_time}</div>
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>付款人<br />付款时间</div>,
        default: ({ row }) => <div>
          <div>{row.payment_user}</div>
          <div>{row.payment_time}</div>
        </div>
      }
    },
    {
      minWidth: 180, slots: {
        header: () => <div>备注</div>,
        default: ({ row }) => <div>
          <VText title='采购备注' value={row.remark} line={1} />
          <VText title='审核驳回原因' value={row.audit_remark} line={1} />
          <VText title='出纳驳回原因' value={row.reject_reason_name} line={1} />
        </div>
      }
    },
    {
      title: '操作', width: 120, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { payment_status } = row
          // payment_status	付款单状态 1待提交 2待审核 3审核中 4待付款 5已驳回 6已作废 7已付款 8待还款 9已还款
          return [<div class='nm flex flex-wrap gap-x-2'>
            <VButton auth="/purchase/finance/payment/view" link type="primary" onClick={() => handleRow('look', row)}>查看</VButton>
            {[1, 5].includes(payment_status) ? <VButton auth="/purchase/finance/payment/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton> : ''}
            {[1, 5].includes(payment_status) ? <VButton auth="/purchase/finance/payment/submit" link type="primary" onClick={() => handleRow('submit', row)}>提交</VButton> : ''}
            {[4].includes(payment_status) ? <VButton auth="/purchase/finance/payment/pay" link type="primary" onClick={() => handleRow('pay', row)}>付款</VButton> : ''}
            {[4].includes(payment_status) ? <VButton auth="/purchase/finance/payment/cashierReject" link type="primary" onClick={() => handleRow('cashierReject', row)}>出纳驳回</VButton> : ''}
            {[1].includes(payment_status) ? <VButton auth="/purchase/finance/payment/printPayment" link type="primary" onClick={() => handleRow('printPay', row)}>打印付款单</VButton> : ''}
            {[1].includes(payment_status) ? <VButton auth="/purchase/finance/payment/printDetail" link type="primary" onClick={() => handleRow('printDetail', row)}>打印付款明细</VButton> : ''}
            {/* {[1].includes(payment_status) ? <el-button link type="primary" onClick={() => handleRow('contract', row)}>合同预览</el-button> : ''} */}
            {[1].includes(payment_status) ? <VButton auth="/purchase/finance/payment/void" link type="primary" onClick={() => handleRow('cancel', row)}>作废</VButton> : ''}
            <VButton auth="/purchase/finance/payment/logs" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>]
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        totalRef?.value.update({ ...form, ...page })
        return api.query({ ...form, ...page })
      }
    }
  }
})
</script>
  